﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace PartyCraftServer.Web.Pages
{
    public class Login : WebHandler
    {
        const string MinecraftAuthUrl = "http://login.minecraft.net?user={0}&password={1}&version=12";
        public override void HandleRequest(HttpListenerContext Context)
        {
            if (PartyCraft.WebService.LoggedInUsers.ContainsKey(Context.Request.RemoteEndPoint.Address.ToString()))
            {
                Redirect(Context, "/home");
                return;
            }
            var post = ParsePost(Context);
            if (!post.ContainsKey("username") || !post.ContainsKey("password"))
            {
                Redirect(Context, "/?fail=1");
                return;
            }

            if (PartyCraft.Settings.GetBoolean("server.debugenabled") == true)
            {
                if (post["username"] == "TestUser" && post["password"] == "password")
                {
                    PartyCraft.WebService.LoggedInUsers.Add(Context.Request.RemoteEndPoint.Address.ToString(),
                            new AuthenticatedEndPoint("TestUser", DateTime.Now.AddHours(1)));
                    Redirect(Context, "/home");
                    PartyCraft.Log("TestUser logged into the web panel.");
                    return;
                }
            }

            if (PartyCraft.Settings.ContainsKey("player." + post["username"] + ".op")
                && PartyCraft.Settings.GetBoolean("player." + post["username"] + ".op"))
            {
                // Authenticate with minecraft.net
                WebClient c = new WebClient();
                string s = c.DownloadString(string.Format(MinecraftAuthUrl, post["username"], post["password"]));
                if (s == "Bad login")
                {
                    Redirect(Context, "/?fail=1");
                    return;
                }
                string[] parts = s.Split(':');
                PartyCraft.WebService.LoggedInUsers.Add(Context.Request.RemoteEndPoint.Address.ToString(),
                    new AuthenticatedEndPoint(parts[2], DateTime.Now.AddHours(1)));
                PartyCraft.Log(parts[2] + " logged into the web panel.");
                Redirect(Context, "/home");
            }
            else
            {
                // Failed to authenticate
                Redirect(Context, "/?fail=1");
            }
        }
    }
}
